
var randomId = createUUID();
var categoryDict = {};
$.fn.loadCategory = function(){
    var categoryUrl = "/api/category/list";
    var categoryList = [];
    var target = this;
    var dataset = $(target).data();
    var categoryPid = "-1";
    var categoryId = "-1";
    if(typeof(dataset) == "object" && typeof(dataset["id"]) == "string"){
        categoryPid = dataset["pid"];
        categoryId = dataset["id"];
    }

    $.get(categoryUrl,function(data){
        var parentId = "p_"+randomId;
        var childId = "c_"+randomId;
        var html = "<label for=\""+parentId+"\">Category:</label>";
        html += "<div class=\"row\"><div class=\"col-md-6 col-xs-9\">";
        html += "<select id=\""+parentId+"\" onchange=\"onParentCategoryChanged(this)\" class=\"form-control\">";
        html += "<option value=\"0\">Select a category</option>";
        var loadChildren = false;
        for(i in data){
            var c = data[i];
            categoryDict[c.id] = c.children;
            if(c.id === categoryPid){
                html += "<option selected='selected' value=\""+c.id+"\">"+c.name+"</option>";
                loadChildren = true;
            }else{
                html += "<option value=\""+c.id+"\">"+c.name+"</option>";
            }
        }
        html += "</select>";
        html += "</div>";
        html += "<div class=\"col-md-6 col-xs-9\"><select class=\"form-control\" id=\""+childId+"\">";
        if(loadChildren){
            var childrenCategories = categoryDict[categoryPid];
            for(i in childrenCategories){
                var c = childrenCategories[i];
                if(c.id === categoryId){
                    html += "<option selected='selected' value=\""+c.id+"\">"+c.name+"</option>";
                }else{
                    html += "<option value=\""+c.id+"\">"+c.name+"</option>";
                }
            }
        }
        html += "</select></div>";
        html += "</div>";
        $(target).html(html);
    }).fail(function(er){
        alert("Load category error.")
        console.log(JSON.stringify(er));
    });
}


function onParentCategoryChanged(e){
    var value = $(e).val();
    if(value === "0")return;
    var children = categoryDict[value];
    if(children == null || typeof(children) == "undefined")
        return;
    var childSel = $("#c_"+randomId);
    childSel.html("");
    var html = "<option value=\"0\">Select a category</option>";
    for(i in children){
        var c = children[i];
        html += "<option value=\""+c.id+"\">"+c.name+"</option>";
    }
    childSel.html(html);
}

function createUUID() {
   return 'xxxxxxxx_xxxx_xxxx_yxxx_xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
   });
}